package 富婆梦.第一阶段.第八周Scoket.聊天程序;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Iterator;

/**
 * @ProjectName: java-learning
 * @Package: 富婆梦.第一阶段.第八周Scoket
 * @ClassName: SimpleChatServer
 * @Author: hemengjin
 * @Description: 聊天对话框，服务端。
 * 实现内容：支持多个客户端连接，将客户端发过来的信息，转发给每一个客户端
 * 方法：
 * 1、go()：运行服务端，提供连接端口
 * 2、getClientMessage()：接受客户端消息
 * 3、sendEveryone（）：将客户端消息告诉每一个客户端
 * @Date:2021/9/20 16:18
 * @Version: 1.0
 */
public class SimpleChatServer {
    ArrayList clientOutputStream;
    Socket sock;

    //运行服务端，提供连接端口,支持多个客户端同时连接
    private void go() {
        clientOutputStream = new ArrayList();
        try {
            ServerSocket serverSocket = new ServerSocket(8888);
            while (true) {
                sock = serverSocket.accept();
                System.out.println("一个客户端已连接");
                //保存每一个客户端的输出流
                PrintWriter writer = new PrintWriter(sock.getOutputStream());
                clientOutputStream.add(writer);

                Thread t = new Thread(new ClientHandler());
                t.start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //接受客户端消息
    private void getClientMessage() {
        try {
            InputStreamReader inputStreamReader = new InputStreamReader(sock.getInputStream());
            BufferedReader reader = new BufferedReader(inputStreamReader);
            String message;
            while ((message = reader.readLine()) != null) {
                System.out.println("接受到客户端信息：" + message);
                sendEveryone(message);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //将消息发送给每一个客户端
    public void sendEveryone(String message) {
        Iterator it = clientOutputStream.iterator();
        while (it.hasNext()) {
            try {
                PrintWriter writer = (PrintWriter) it.next();
                writer.println(message);
                writer.flush();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        System.out.println("已经将信息发送给每一个客户端了！");
    }

    public class ClientHandler implements Runnable {

        public void run() {
            while (true){
                getClientMessage();
            }

        }
    }

    public static void main(String[] args) {
        SimpleChatServer server = new SimpleChatServer();
        server.go();
    }
}
